from flask import Flask, request, render_template, jsonify, redirect, url_for

from tools.utils import *
from tools.pymysql_ import PyMysql
import pandas as pd


app = Flask(__name__)

# 调用数据库对象
mysql_ = PyMysql()


@app.route('/')
def index():
    """
        重定向, 访问127.0.0.1 发生重定向, 跳转127.0.0.1/index
    :return:
    """
    return redirect(url_for('main'))


@app.route('/index')
def main():
    return render_template('main.html')


@app.route('/time')
def gettime_api():
    return get_time()


@app.route('/today')
def today_data_api():
    # 调用工具函数, 将表数据转换成pandas函数
    df = mysql_.to_pandas(table='today_show')
    data = df.to_dict(orient='records')
    return jsonify({'data': data})


@app.route('/area_data/<string:epi>')
def get_map_data_api(epi):
    # 调用工具函数, 将表数据转换成pandas函数
    df = mysql_.to_pandas(table='area_show')
    if epi == "all_con":
        df_area = df[['area_name', 'confirm']]
    elif epi == "now_con":
        df_area = df[['area_name', 'now_confirm']]
    elif epi == "all_dead":
        df_area = df[['area_name', 'dead']]
    else:
        df_area = df[['area_name', 'confirm']]
    area_data = df_area.to_dict(orient='records')
    for area in area_data:
        k2 = [k for k in area.keys()][1]
        area['name'] = area['area_name']
        area['value'] = area[k2]
        del area['area_name']
        del area[k2]
    print(area_data)
    area_d = sorted(area_data, key=lambda area_data: area_data['value'], reverse=True)
    return jsonify({"data": area_d})


@app.route('/every_month')
def every_month_data_api():
    df = mysql_.to_pandas(table='history')
    # 将ds列处理成索引
    df.index = pd.to_datetime(df['ds'])
    # 将索引格式化成 年-月 时间字符串
    df.index = df.index.strftime('%Y-%m')
    # 将数据根据每个年月索引进行分组, 选出每个组的最后一个或者第一个.
    df = df.groupby(df.index).last()
    df_data = df[['ds', 'confirm', 'now_confirm', 'heal', 'dead', 'input', 'confirm_add', 'heal_add', 'dead_add', 'input_add']]
    data = df_data.to_dict(orient='records')
    data_dict = {
        'ds': [d['ds'].strftime('%Y-%m-%d') for d in data],
        'confirm': [d['confirm'] for d in data],
        'now_confirm': [d['now_confirm'] for d in data],
        'heal': [d['heal'] for d in data],
        'dead': [d['dead'] for d in data],
        'input': [d['input'] for d in data],
        'confirm_add': [d['confirm_add'] for d in data],
        # 治愈增加人数等于今日治愈-昨日治愈
        'heal_add': heal_head_add(data),
        # 死亡增加人数等于今日死亡-昨日死亡
        'dead_add': heal_head_add(data, live=0),
        'input_add': [d['input_add'] for d in data],
    }
    return jsonify({'data': data_dict})


@app.route('/month_count')
def get_count():
    df = mysql_.to_pandas(table='history')
    # 将ds列处理成索引
    df.index = pd.to_datetime(df['ds'])
    # 将索引格式化成 年-月 时间字符串
    df.index = df.index.strftime('%Y-%m')
    # 将数据根据每个年月索引进行分组, 选出每个组的最后一个或者第一个.
    # df = df.groupby(df.index).agg(lambda x: sum(x['heal']))
    # df = df.groupby(df.index).agg(lambda x: sum(x['dead']))
    df_data = df[['ds', 'heal', 'dead']]
    data = df_data.to_dict(orient='records')
    data_dict = {
        'ds': [d['ds'].strftime('%Y-%m') for d in data],
        'heal_add': heal_head_add(data),
        'dead_add': heal_head_add(data, live=0)
    }
    df = pd.DataFrame(data_dict)
    df = df.groupby("ds").sum()
    df = df.reset_index()
    data = df.to_dict(orient='records')
    data_ = {
        'ds': [d['ds'] for d in data],
        'heal': [d['heal_add'] for d in data],
        'dead': [d['dead_add'] for d in data],
    }
    return jsonify({'data': data_})


@app.errorhandler(404)
def page_not_found(error):
    """
        访问的url不存在, 404
    :param error:
    :return:
    """
    return render_template('page_not_found.html'), 404


@app.errorhandler(403)
def page_not_found(error):
    """
        拒绝请求
    :param error:
    :return:
    """
    return render_template('not_request.html'), 403


if __name__ == '__main__':
    app.run()
